//
//  SystemSetViewController.m
//  QRMaster
//
//  Created by myApple on 15/4/29.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "SystemSetViewController.h"

#import "GesturePasswordController.h"
#import "ModifyPWDViewController.h"
#import "aboutViewController.h"
#import "FeedBackViewController.h"
#import "StartPageController.h"
#import "SDImageCache.h"
#import "PromptInfoView.h"
#import "OpertionPlist.h"
#import "GuestViewController.h"
#import "TouchBtnColor.h"
#import "RecoderShareCardController.h"
#import "localizControllerViewController.h"
#import "InternationalControl.h"
#import "AppDelegate.h"

#define FONT [UIFont systemFontOfSize:16.0]

@interface SystemSetViewController ()<UIActionSheetDelegate>
{
    UISwitch * gestureSwitch;
    NSUserDefaults * userInfo;
    UILabel * gestureLabel;

    UITableView *settingTableView;
    NSMutableDictionary *titleDic;    //存放每个cell前的title
    NSMutableArray *systemTitleArray; //系统操作title
    NSMutableArray *personTitleArray; //个人操作title
    NSMutableArray *loginTitleArray;  //登录操作title
    
    BOOL isOpenFlag ;                //是否打开用户指引
}

@end

@implementation SystemSetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    userInfo = [NSUserDefaults standardUserDefaults];
    self.view.backgroundColor = RGBA(237, 238, 241, 1);
    [self initData];
    isOpenFlag = NO;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self initData];
    self.title = NSLocalizedString(@"setting", nil);
    isOpenFlag = NO;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark ------初始化数组
-(void)initData
{
    //整个tableView Group
    titleDic=[[NSMutableDictionary alloc]init];
    
    //section 二
    systemTitleArray=[[NSMutableArray alloc]initWithObjects:NSLocalizedString(@"mineCache", nil),NSLocalizedString(@"shareList", nil),NSLocalizedString(@"feedBack", nil),NSLocalizedString(@"lauguage", nil),NSLocalizedString(@"mineGuide", nil), nil];
    //section 一
    personTitleArray=[[NSMutableArray alloc]initWithObjects:NSLocalizedString(@"modifyGesturePWD", nil),NSLocalizedString(@"soundSwitch", nil),NSLocalizedString(@"quickEnter", nil),NSLocalizedString(@"modifyPWD", nil), nil];
    //section 三
    loginTitleArray=[[NSMutableArray alloc]initWithObjects:NSLocalizedString(@"mineAbout", nil),NSLocalizedString(@"quit", nil), nil];
    
    [titleDic setObject:personTitleArray forKey:@"0"];
    [titleDic setObject:systemTitleArray forKey:@"1"];
    [titleDic setObject:loginTitleArray forKey:@"2"];
    settingTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT-64) style:UITableViewStyleGrouped];
    settingTableView.delegate=self;
    settingTableView.dataSource=self;
    [self.view addSubview:settingTableView];
}

#pragma mark -UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [[titleDic allKeys] count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[titleDic objectForKey:[[titleDic allKeys] objectAtIndex:section]] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *leftIdentifier = @"SettingIndentifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:leftIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:leftIdentifier];
        
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    }
    for (UIView *vw in cell.contentView.subviews) {
        [vw removeFromSuperview];
    }
    cell.textLabel.text=[[titleDic objectForKey:[NSString stringWithFormat:@"%ld",(long)indexPath.section]] objectAtIndex:indexPath.row];
    
    if (indexPath.section==0 && indexPath.row == 1) {
        UISwitch * soundSwitch = [[UISwitch alloc]initWithFrame:CGRectMake(UI_SCREEN_WIDTH-60, 5, 40, 40)];
        if ([[userInfo objectForKey:@"sound"] isEqualToString:@"1"]) {
            soundSwitch.on = YES;
        }
        else
        {
            soundSwitch.on = NO;
        }
        
        [soundSwitch addTarget:self action:@selector(soundSwitch:) forControlEvents:UIControlEventValueChanged];
        [cell.contentView addSubview:soundSwitch];

    }
    else if (indexPath.section==0 && indexPath.row == 2)
    {
        UISwitch * quickSwitch = [[UISwitch alloc]initWithFrame:CGRectMake(UI_SCREEN_WIDTH-60, 5, 40, 40)];
        if ([[userInfo objectForKey:@"quickCard"] isEqualToString:@"1"]) {
            quickSwitch.on = YES;
        }
        else
        {
            quickSwitch.on = NO;
        }
        
        [quickSwitch addTarget:self action:@selector(openQuickSwitch:) forControlEvents:UIControlEventValueChanged];
        [cell.contentView addSubview:quickSwitch];
    }
    else if (indexPath.section==1 && indexPath.row == 4)
    {
        UISwitch * userGuideSwitch = [[UISwitch alloc]initWithFrame:CGRectMake(UI_SCREEN_WIDTH-60, 5, 40, 40)];
        userGuideSwitch.on = isOpenFlag;
        [userGuideSwitch addTarget:self action:@selector(openUserGuide:) forControlEvents:UIControlEventValueChanged];
        [cell.contentView addSubview:userGuideSwitch];

    }
    else
    {
        UIImageView * guestImgView = [[UIImageView alloc]initWithFrame:CGRectMake(UI_SCREEN_WIDTH-40, 15, 20, 20)];
        guestImgView.image = [UIImage imageNamed:@"36右箭头"];
        [cell.contentView addSubview:guestImgView];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            [self guestClick];
        }
        else if (indexPath.row == 3) {
            [self LoginPWDClick];
        }
    }
    else if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            [self CacheClick];
        }
        else if (indexPath.row == 1) {
            [self ShareClick];
        }
        else if (indexPath.row == 2) {
            [self FeedBackClick];
        }
        else if (indexPath.row == 3) {
            [self localizClick];
        }
    }
    else if (indexPath.section == 2) {
        if (indexPath.row == 0) {
            [self AboutClick];
        }
        else if (indexPath.row == 1) {
            [self QuitClick];
        }
    }

}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    float height=5;
    if(section==0)
    {
        height=0.1;
    }
    return height;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    float height=5;
    if(section==0)
    {
        height=5;
    }
    
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, height)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}


/**
 *  函数描述：修改手势密码跳转
 *  输入参数：无
 *  输出参数：无
 *  返回值：  无
 */
-(void)guestClick
{
    GuestViewController * gvc = [[GuestViewController alloc]init];
    [self.navigationController pushViewController:gvc animated:YES];
}


/**
 *  函数描述：点击修改声音的开关切换
 *  输入参数：UISwitch的对象
 *  输出参数：无
 *  返回值：  无
 */
-(void)soundSwitch:(UISwitch *)ch
{
    if (ch.on) {
        [userInfo setValue:@"1" forKey:@"sound"];
    }
    else
    {
        [userInfo setValue:@"0" forKey:@"sound"];
    }
    [userInfo synchronize];
    [settingTableView reloadData];
}


/**
 *  函数描述：点击修改手势密码的开关切换
 *  输入参数：UISwitch的对象
 *  输出参数：无
 *  返回值：  无
 */
-(void)openQuickSwitch:(UISwitch *)quick
{
    if (quick.on) {
        [userInfo setValue:@"1" forKey:@"quickCard"];
    }
    else
    {
        [userInfo setValue:@"0" forKey:@"quickCard"];
    }
    [userInfo synchronize];
    [settingTableView reloadData];
}

/**
 *   函数描述：修改密码跳转
 *   输入参数：无
 *   输出参数：无
 *   返回值：  无
 */
-(void)LoginPWDClick
{
   ModifyPWDViewController * mfvc = [[ModifyPWDViewController alloc]init];
    [self.navigationController pushViewController:mfvc animated:YES];
}


/**
 *  函数描述：清除缓存
 *  输入参数：无
 *  输出参数：无
 *  返回值：  无
 */
-(void)CacheClick
{
    [[SDImageCache sharedImageCache]clearDisk];
    [[SDImageCache sharedImageCache]clearMemory];
    NSString * homePath = [NSString stringWithFormat:@"%@/Library/Caches/uclbrt.com.QRMaster/fsCachedData",NSHomeDirectory()];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    NSArray * fileArray = [fileManager contentsOfDirectoryAtPath:homePath error:nil];
    for (NSString * str in fileArray) {
        NSString * filePath = [homePath stringByAppendingString:str];
        [fileManager removeItemAtPath:filePath error:nil];
    }
    [PromptInfoView showMessage:NSLocalizedString(@"cachePromt", nil)];
}

-(void)ShareClick
{
    RecoderShareCardController * rsc = [[RecoderShareCardController alloc]init];
    [self.navigationController pushViewController:rsc animated:YES];
}

-(void)FeedBackClick
{
    FeedBackViewController * fbvc = [[FeedBackViewController alloc]init];
    [self.navigationController pushViewController:fbvc animated:YES];
}

-(void)localizClick
{
    localizControllerViewController * lcv = [[localizControllerViewController alloc]init];
    [self.navigationController pushViewController:lcv animated:YES];
}

-(void)openUserGuide:(UISwitch *)openSwitch
{
    [userInfo setValue:@"yes" forKey:@"middle"];             //快捷按钮提示操作
    [userInfo setValue:@"yes" forKey:@"share"];              //分享按钮提示操作
    [userInfo setValue:@"yes" forKey:@"setlock"];            //授权分配卡切换提示操作
    [userInfo setValue:@"yes" forKey:@"faverit"];            //收藏房卡提示操作
    [userInfo setValue:@"yes" forKey:@"address"];            //从通讯录添加成员
    [userInfo setValue:@"yes" forKey:@"changeCommunity"];    //切换集群提示操作
    [userInfo setValue:@"yes" forKey:@"longPress"];          //长按分享
    [userInfo synchronize];
    isOpenFlag = openSwitch.on;
    [settingTableView reloadData];
}

-(void)AboutClick
{
    aboutViewController * avc = [[aboutViewController alloc]init];
    [self.navigationController pushViewController:avc animated:YES];
}

-(void)QuitClick
{
    UIActionSheet * quitAcitonSheet = [[UIActionSheet alloc]initWithTitle:NSLocalizedString(@"quitSheet", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"alterCancel", nil) destructiveButtonTitle:NSLocalizedString(@"quit", nil) otherButtonTitles:nil];
    [quitAcitonSheet showInView:self.view];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self logOut];
    }
}


/**
 *  函数描述：退出登录，清除token,手势，以及本地文件
 *  输入参数：无
 *  输出参数：无
 *  返回值：  无
 */
-(void)logOut
{
    [userInfo setValue:nil forKey:@"token"];
    [userInfo setValue:nil forKey:@"login"];
    NSMutableDictionary * data = [OpertionPlist readDataFromPlist];
    [data setValue:nil forKey:HOUSEINFO];
    [data setValue:nil forKey:STAFFINFO];
    [data setValue:nil forKey:COMMUNITYINFOFORKEY];
    [OpertionPlist writeDataToPlist:data];
    GesturePasswordController * gpc = [[GesturePasswordController alloc]init];
    [gpc clear];
    [userInfo setValue:@"0" forKey:@"gesture"];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:@"logout" forKey:@"startUp"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"startUp" object:postDict];
}
@end
